// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const {
    orderId,
    deliveryManId
  } = event // { orderId, deliveryManId }

  const {
    order,
    addr,
    deliveryMen
  } = await findDeliveryUsers(orderId, deliveryManId)
  const resultList = []

  for (const man of deliveryMen) {
    resultList.push(await sendMsg(order, addr, man))
    resultList.push(await sendSms(order, man))
  }
  console.log(resultList)
  return resultList
}

async function sendMsg(order, addr, man) {
  const orderId = order._id
  const search = JSON.stringify({
    orderId
  })
  return await cloud.callFunction({
    name: 'sendMsg',
    data: {
      touser: man._openid, // openid of user
      page: `/pages/order/order-list/index?action=manage&search=${search}`,
      amount: order.totalFee,
      title: '新订单提醒',
      remark: order.remark || ('订单尾号：' + orderId.substr(orderId.length - 15)),
      datetime: order.createTime + '',
      addr: addr.mobile + ',' + addr.name
    }
  })
}

async function sendSms(order, man) {
  const strDate = (await cloud.callFunction({
    name: 'tools',
    data: {
      action: 'dateTool.format',
      timestamp: order.createTime + '',
      format: 'M月d日hh点'
    }
  })).result

  return await cloud.callFunction({
    name: 'sendSmsTc',
    data: {
      templateName: "new_order",
      templateParamList: [strDate, "1"],
      phoneNumberList: ["+86" + man.phoneNumber],
      sessionContext: 'notify new order'
    }
  })
}

async function findDeliveryUsers(orderId, deliveryManId) {
  const _ = db.command
  // order信息
  const orderRes = await db.collection('orders')
    .where({
      _id: _.eq(orderId)
    })
    .get()
  const order = orderRes.data[0]
  // console.log(order)

  // 用户地址
  const addrRes = await db.collection('delivery_addr')
    .where({
      _openid: _.eq(order._openid)
    })
    .get()
  const addr = addrRes.data[0]
  // console.log(addr)

  // 配送员或店长
  const strShopId = addr.shop + '',
    nShopId = parseInt(addr.shop + '')
  const userRes = await db.collection('users')
    .where(_.and({
      _id: deliveryManId ? _.eq(deliveryManId) : _.exists(true)
    }, {
      role: _.or(_.eq('delivery'), _.eq('master')),
    }, _.or({
      shop: {
        id: nShopId
      }
    }, {
      shop: {
        id: strShopId
      }
    })))
    .get()
  const deliveryMen = userRes.data
  // console.log(addr, deliveryMen)
  return {
    order,
    addr,
    deliveryMen
  }
}